
package com.insigma.business.qrcode.common._bff.impl;

import cn.hutool.core.util.ClassUtil;
import com.google.common.collect.Lists;

import com.insigma.business.qrcode.common.dto.CommonEnumLabel;
import com.insigma.business.qrcode.common.dto.CommonTmpInfoUpdateRequest;
import com.insigma.business.qrcode.common.dto.SystemConfigDTO;
import com.insigma.business.qrcode.common._bff.SystemConfigBFFProvider;
import com.insigma.business.qrcode.common._consumer.SystemConfigConsumer;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.CommonConstant;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.util.RpcContextUtil;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.common.vo.DescEnum;
import com.insigma.business.qrcode.common.vo.SessionSoldier;
import com.insigma.business.qrcode.soldier.dto.SimpleApiRequest;
import com.insigma.business.qrcode.soldier.dto.ValueLabelEnum;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Slf4j
@Service
@Component("systemConfigBFFProvider")
public class SystemConfigBFFProviderImpl extends BaseProviderImpl implements SystemConfigBFFProvider {

    @Autowired
    private SystemConfigConsumer systemConfigConsumer;

    private Map<String, List<CommonEnumLabel>> enumsMap = new HashMap<>();


    @Override
    public BaseResponse<String> getCustomerServcieInfo() {

        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
            }

            @Override
            public void executeService() {
                final SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
                final String visitorId = RpcContextUtil.getSessionBasis() == null ? null : RpcContextUtil.getSessionBasis().getVisitorId();
                if (sessionSoldier == null && StringUtils.isNotBlank(visitorId)) {

                }

                final SystemConfigDTO auth2FullUrlSystemConfigDTO = systemConfigConsumer.getSystemConfigByName(CommonConstant.SYSTEM_CONFIG_ITEM_NAME_ALIPAY_LIFE_OAUTH2_FULL_URL).getDto();
                BizCheckUtil.checkNotNull(auth2FullUrlSystemConfigDTO, "支付宝生活号授权URL未初始化");
                BizCheckUtil.checkNotBlank(auth2FullUrlSystemConfigDTO.getValue(), "支付宝生活号授权URL初始化值错误");

                baseResponse.setDto(auth2FullUrlSystemConfigDTO.getValue());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.ALIPAY_LIFE_OAUTH2_URL_GET;
            }
        });

        return baseResponse;
    }

    @Override
    public BaseResponse<String> getThirdAreaShow() {
        final SystemConfigDTO systemConfigDTO = systemConfigConsumer.getSystemConfigByName("THIRD_AREA_SWITCH").getDto();
        if (systemConfigDTO != null) {
            return ResponseUtils.buildSuccessResponse(systemConfigDTO.getValue());
        }
        return ResponseUtils.buildSuccessResponse("0");
    }

    @Override
    public BaseResponse<List<CommonEnumLabel>> getEnum(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getId(), "id不能为空");

        List<CommonEnumLabel> commonEnumLabels = enumsMap.get(request.getId());
        if (commonEnumLabels == null) {
            commonEnumLabels = findEnum(request.getId());
        }
        return ResponseUtils.buildSuccessResponse(commonEnumLabels);
    }

    @Override
    public BaseResponse<String> getContactNo(SimpleApiRequest request) {
        String base = getImageStrFromUrl(request.getUrl());

        return new BaseResponse(true, base);
    }

    @Override
    public BaseResponse<String> html2Pdf(CommonTmpInfoUpdateRequest request) {

        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        return systemConfigConsumer.html2Pdf(request);
    }


    public static String getImageStrFromUrl(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {

            URL url = new URL(imgURL);
            byte[] by = new byte[1024];

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();

            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }

            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }


    private List<CommonEnumLabel> findEnum(String id) {
        synchronized (this) {
            List<CommonEnumLabel> value = enumsMap.get(id);
            if (value == null) {
                log.info("加载枚举：{}", id);
                Set<Class<?>> classes = ClassUtil.scanPackage("com.sycloud.ss.main.data.enums");
                for (Class<?> aClass : classes) {
                    String simpleName = aClass.getSimpleName();
                    if (id.equals(simpleName)) {
                        if (aClass.isEnum()) {
                            Class<Enum> enumClass = (Class<Enum>) aClass;
                            Enum[] enumConstants = enumClass.getEnumConstants();

                            List<CommonEnumLabel> item = Lists.newArrayList();
                            for (Enum enumConstant : enumConstants) {
                                String name = enumConstant.name();
                                if (enumConstant instanceof DescEnum) {
                                    if (enumConstant instanceof ValueLabelEnum) {
                                        ValueLabelEnum desc = (ValueLabelEnum) enumConstant;
                                        item.add(new CommonEnumLabel(desc.getValue(), desc.getLabel()));
                                    } else {
                                        DescEnum desc = (DescEnum) enumConstant;
                                        item.add(new CommonEnumLabel(name, desc.getDesc()));
                                    }

                                }
                            }
                            enumsMap.put(simpleName, item);
                            return item;
                        }
                        break;
                    }
                }
                enumsMap.put(id, Lists.newArrayList());
                return Lists.newArrayList();
            }
            return value;
        }
    }

    private void initEnumsMap() {
        if (enumsMap == null) {
            synchronized (this) {
                if (enumsMap == null) {
                    enumsMap = new HashMap<>();
                    Set<Class<?>> classes = ClassUtil.scanPackage("com.sycloud.ss.main.data.enums");
                    for (Class<?> aClass : classes) {
                        String simpleName = aClass.getSimpleName();
                        if (aClass.isEnum()) {
                            Class<Enum> enumClass = (Class<Enum>) aClass;
                            Enum[] enumConstants = enumClass.getEnumConstants();

                            List<CommonEnumLabel> item = Lists.newArrayList();
                            for (Enum enumConstant : enumConstants) {
                                String name = enumConstant.name();
                                if (enumConstant instanceof DescEnum) {
                                    DescEnum desc = (DescEnum) enumConstant;
                                    item.add(new CommonEnumLabel(name, desc.getDesc()));
                                }
                            }
                            enumsMap.put(simpleName, item);
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {





















    }
}
